package com.laputa.service.method.impl;

import com.laputa.dao.model.Ground;
import com.laputa.model.City;
import com.laputa.model.manager.CityManager;
import com.laputa.model.manager.GroundManager;
import com.laputa.model.manager.UserManager;
import com.laputa.service.method.BuyService;
import com.laputa.service.model.MainFrameData;
import com.laputa.system.Lib;

public class BuyServiceImpl implements BuyService {
	private UserManager userManager;
	private CityManager cityManager;
	private GroundManager groundManager;
	private MainFrameData mainFrameData;
	
	public void setUserManager(UserManager userManager){
		this.userManager = userManager;
	}
	
	public void setCityManager(CityManager cityManager){
		this.cityManager = cityManager;
	}
	
	public void setGroundManager(GroundManager groundManager){
		this.groundManager = groundManager;
	}
	
	public void setMainFrameData(MainFrameData mainFrameData){
		this.mainFrameData = mainFrameData;
	}
	
	public boolean buy(String userID, String groundID) {
		Long money = userManager.getMoney(userID);
		Ground ground = groundManager.getGround(groundID);
		Long price = ground.getPrice();
		if (money < price)
			return false;
		else{
			Long currentUserID = ground.getUser();
			int buildtime = Lib.getCurrentTime();
			money -= price;
			groundManager.saveUserBuildTime(groundID, userID, buildtime);
			userManager.saveMoney(userID, money.toString());
			
			Long currentUserMoney = userManager.getMoney(currentUserID.toString());
			currentUserMoney += price;
			userManager.saveMoney(currentUserID.toString(), currentUserMoney.toString());
			return true;	   
		}
	}
	
	public MainFrameData getMainFrameData(String userID) {
		Long id =  Long.parseLong(userID);
		City city = cityManager.getCityObject(userManager.getUser(id.toString()).getCity().toString(), id.toString());
		com.laputa.dao.model.User user = userManager.getUser(userID); 
		String name = user.getName();
		this.mainFrameData.setId(id);
		this.mainFrameData.setName(name);
		this.mainFrameData.setCity(city);
		this.mainFrameData.setMoney(user.getMoney());
		return this.mainFrameData;
	}
}
